class PostsController < ApplicationController
    include AuthenticatedSystemBrowse
    before_filter :login_required, :only => [ :new, :create, :edit, :update, :destroy, :voteuseless, :voteuseful ]
  
    #caches_action_content :show
    #cache_sweeper :post_sweeper, :only => [:update]
  
    def index
    	if !params[:group_id].nil?
            @group = Group.find(params[:group_id])
            @posts = GroupPost.find_all_by_group_id(params[:group_id], :include => [:user, :group ], :order => 'replied_at desc', :limit => 15)
            render_posts_or_xml(action_name, "group")
        elsif !params[:site_id].nil?
            @site = Site.find(params[:site_id])
            @posts = SitePost.find_all_by_site_id(params[:site_id], :include => [:user, :site ], :order => 'replied_at desc', :limit => 15)
            render_posts_or_xml(action_name, "site")
        end
    end
    
    #group, common, site是首页使用的3个rss
    def group
    	@posts = GroupPost.find(:all, :include => [:user, :group ], :order => 'replied_at desc', :limit => 15)
        render_posts_or_xml(action_name, "group")
    end
    
    def common
        @posts = CommonPost.find(:all, :include => [:user, :post_category, {:community => :district} ], :order => 'replied_at desc', :limit => 15)
        render :action => "common.rxml", :layout => false
    end
    
    def site
        @posts = SitePost.find(:all, :include => [:user, :site ], :order => 'replied_at desc', :limit => 15)
        render :action => "site.rxml", :layout => false
    end
    
    def show
        @post = Post.find(params[:id], :include => [:user, :replies])
        @replies = @post.replies
        
        @reply = Reply.new
        @reply.title = "re:" + @post.title
        
        @tags = Tag.find_by_sql("select tags.id, tags.name, count(*) as count  from taggings, tags, posts  where tags.id = taggings.tag_id and posts.id = #{@post.id} and posts.id = taggings.taggable_id and taggings.taggable_type = 'Post' group by tag_id")
        @page_title = @post.title
        
        #根据tag发现相关的6个帖子
        @related_posts = Array.new
	for tag in @tags
            if @related_posts.size > 10
                break
            end
            @related_posts += Post.find_tagged_with(:any => tag.name, :limit=>10, :offset=>0, :order=>'updated_at DESC')
	end
	@related_posts = @related_posts.uniq
	@related_posts.delete(@post)
	if @related_posts.size > 6
            @related_posts = @related_posts[0..5]
	end
        
        respond_to do |format|
            format.html do
                @posts_of_same_cat = posts_of_same_cat(@post)
                render_post_or_xml
            end
            format.rss  do
                if @post.class == CommonPost
                  render_posts_or_xml(action_name, "common")
                elsif @post.class == SitePost
                  render_posts_or_xml(action_name, "site")
                else
                  render_posts_or_xml(action_name, "group")
                end
            end
        end
    end
  
    def new
        if current_user.community.nil?
            flash[:notice] = "你需要定居后才能发帖!"
            redirect_back_or_default(:controller => 'communities', :action => 'life' )
        else
            @user_tags = user_tags(current_user.id)
            @all_users_tags = user_tags
            @post = CommonPost.new(params[:post])
            
            @page_title = '发布实用信息'
            @categories = top_post_category
            firstcat = PostCategory.find(:first, :conditions => [ "id = ?", @categories[0][1]])
            @first_cat_children  = firstcat.children.map{|u| [u.title, u.id]}
        end
    end
  
    def create
        @user_tags = user_tags(current_user.id)
        @all_users_tags = user_tags
        @categories = top_post_category
        firstcat = PostCategory.find(:first, :conditions => [ "id = ?", @categories[0][1]])
        @first_cat_children  = firstcat.children.map{|u| [u.title, u.id]}
        @post = CommonPost.new(params[:post])
        CommonPost.transaction do
            @post.replied_at = Time.now.utc
            @post.user_id = current_user.id
            @post.community_id = current_user.community.id
            @post.district_id = current_user.district.id
            @post.save!  
            @post.tag_with(params[:newpost][:tags])
              
            Tag.parse(params[:newpost][:tags]).each do |name|
                exist_tags = Tag.find_by_sql ["SELECT * FROM tags INNER JOIN user_tags ON tags.id = user_tags.tag_id WHERE tags.name = ? AND user_tags.user_id = ?", name, current_user.id]
                if exist_tags.empty?
                    tag = Tag.find(:first, :conditions => [ "name = ?", name])
                    #current_user.tags.push(tag)
                    user_tag = UserTag.new(:user => current_user, :tag => tag)
                    user_tag.save!
                end
            end
            current_user.add_scores(3)
        end
        redirect_to common_post_url(@post.community.district, @post.community, @post)
        
        rescue ActiveRecord::RecordInvalid
        render :action => 'new'
    end
  	
    def destroy
  	@post = Post.find(params[:id])
  	if @post.user_has_auth_destroy?(current_user)
  	    @post.destroy
  	    flash[:notice] = "删除帖子成功!"
  	    
            #if @post.class == CommonPost
            #   redirect_to community_url(@post.community.district, @post.community)
            #elsif @post.class == GroupPost
            #   redirect_to group_url(@post.group)
            #elsif @post.class == SitePost
            #   redirect_to site_url(@post.site)
            #end
            redirect_post_url(@post)
  	else
  	    raise ActiveRecord::RecordNotFound
  	end
    end
  	
    def cat_changed
        @category = PostCategory.find(:first, :conditions => [ "id = ?", params[:parent_id]])
        if !@category.nil?
            @children = @category.children.map{|u| [u.title, u.id]}
        end
        render :partial=>'childCat'
    end
  
    def edit
        @post = current_user.posts.find(params[:id])
        @page_title = ' - 编辑帖子'
        @tags = Tag.find_by_sql("select tags.id, tags.name  from taggings, tags, posts  where tags.id = taggings.tag_id and posts.id = #{@post.id} and posts.id = taggings.taggable_id and taggings.taggable_type = 'Post' group by tag_id")
        @tags_text = @tags.collect{|n| n.name}.join(' ')
        if @post.class == CommonPost
            @categories = top_post_category
            firstcat = PostCategory.find(:first, :conditions => [ "id = ?", @post.post_category.parent])
            @first_cat_children  = firstcat.children.map{|u| [u.title, u.id]}
        end
    end
  
    def update
        @post = current_user.posts.find(params[:id])
        @tags = Tag.find_by_sql("select tags.id, tags.name  from taggings, tags, posts  where tags.id = taggings.tag_id and posts.id = #{@post.id} and posts.id = taggings.taggable_id and taggings.taggable_type = 'Post' group by tag_id")
        Post.transaction do
            @post.update_attributes(params[:post])
            @post.tag_with(params[:newpost][:tags])
            
            #帖子的tag变更时，要对用户tag进行相应的变更

            #增加了新的tag，在UserTag中插入新的纪录
            Tag.parse(params[:newpost][:tags]).each do |name|
                exist_tags = Tag.find_by_sql ["SELECT * FROM tags INNER JOIN user_tags ON tags.id = user_tags.tag_id WHERE tags.name = ? AND user_tags.user_id = ?", name, current_user.id]
                if exist_tags.empty?
                    tag = Tag.find(:first, :conditions => [ "name = ?", name])
                    user_tag = UserTag.new(:user => current_user, :tag => tag)
                    user_tag.save!
                end
            end
            
            #更新后的tag的数组
            new_tags = Array.new
                Tag.parse(params[:newpost][:tags]).each do |name|
                new_tags << name
            end
            
            #帖子现有的tag
            now_tags = Array.new
                @tags.each do |t|
                now_tags << t.name
            end
	  
            #比较后，得到删除掉的tag，将
            delete_tags = (new_tags + now_tags).uniq - new_tags  
            delete_tags.each do |name|
                tag = Tag.find(:first, :conditions => [ "name = ?", name])
                user_tag = UserTag.new(:user => current_user, :tag => tag)
                #user_tag = UserTag.find(:user => current_user, :tag => tag)
                user_tag.save!
            end
          
            flash[:notice] = '帖子更新成功.'

            #if @post.class == CommonPost
            #    redirect_to common_post_url(@post.community.district, @post.community, @post)
            #elsif @post.class == GroupPost
            #    redirect_to group_post_url(@post.group, @post)
            #elsif @post.class == SitePost
            #    redirect_to site_post_url(@post.site, @post)
            #end
            redirect_post_url(@post)
        end
        rescue ActiveRecord::RecordInvalid
        render :action => 'edit'
    end
  
    def voteuseful
        return unless request.post?
        @post = Post.find(params[:post][:id])
        Post.transaction do
            @post.voteuseful_count = @post.voteuseful_count + 1
            @post.save!
        end
        #set session
        if session[:post_vote].nil?
            session[:post_vote] = Array.new
        end
        session[:post_vote].push(@post.id)
        
        render :text => "<table border=\"0\"><tr><td>#{@post.voteuseful_count}/#{@post.voteuseful_count + @post.voteuseless_count}的人觉得有用，你的投票已经提交，谢谢。</td></tr></table>"
    end
  
    def voteuseless
        return unless request.post?
        @post = Post.find(params[:post][:id])
        Post.transaction do
            @post.voteuseless_count = @post.voteuseless_count + 1
            @post.save!
        end
        #set session
        if session[:post_vote].nil?
            session[:post_vote] = Array.new
        end
        session[:post_vote].push(@post.id)
        
        render :text => "<table border=\"0\"><tr><td>#{@post.voteuseful_count}/#{@post.voteuseful_count + @post.voteuseless_count}的人觉得有用，你的投票已经提交，谢谢。</td></tr></table>"
    end
  
    protected
    def render_posts_or_xml(template_name = action_name, type = "common")
        respond_to do |format|
            format.html { render :action => "#{template_name}_#{type}.rhtml" }
            format.rss  { render :action => "#{template_name}_#{type}.rxml", :layout => false }
            format.xml  { render :xml => @posts.to_xml }
        end
    end
    
    def render_post_or_xml(template_name = action_name)
        respond_to do |format|
            format.html { render :action => "#{template_name}.rhtml" }
            format.rss  { render :action => "#{template_name}.rxml", :layout => false }
            format.xml  { render :xml => @post.to_xml }
        end
    end
end
